package com.zxq.ruoyi.rabbitmq;


import com.alibaba.fastjson.JSON;
import com.zxq.frame.core.ExchangeDTO;
import com.zxq.ruoyi.channel.SynchroniseMessage;
import com.zxq.ruoyi.channel.device.DeviceMessageServiceImpl;
import com.zxq.ruoyi.network.tcp.cache.TcpChannelCache;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.xmlbeans.impl.util.HexBin;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.nio.ByteBuffer;


@Component
@Slf4j
public class RabbitSubscribeHelper {

    @Autowired
    DeviceMessageServiceImpl deviceMessageService;

    /**
     * 数据写给web，协议层把设备数据包拆包后，发送这条通道，用于上传web
     * @param exchangeDTO 交换数据
     * @throws Exception
     */
    @RabbitListener(queues = "${spring.rabbitmq.template.web-queue}")
    public void listenWebChannel(ExchangeDTO exchangeDTO) throws Exception {
        log.info("prepare notify web => " + exchangeDTO.getStringFormatMsg());
        deviceMessageService.deviceResult(exchangeDTO);
    }


    /**
     * 数据写给设备，协议层把web数据包装后，发送这条通道，用于写回设备
     * @param exchangeDTO 交换数据
     * @throws Exception
     */
    @RabbitListener(queues = "${spring.rabbitmq.template.network-queue}")
    public void listenDeviceChannel(ExchangeDTO exchangeDTO) throws Exception {
        log.info("prepare write device => " + exchangeDTO.getStringFormatMsg());
        ByteBuf buffer = Unpooled.copiedBuffer(exchangeDTO.getData());

        ChannelHandlerContext channel = TcpChannelCache.getChannel(exchangeDTO.getDevId());
        if( channel != null) {
            channel.pipeline().writeAndFlush(buffer);
        } else {
            log.info("dev:%s offline",exchangeDTO.getDevId());
        }

    }



}
